package other.system.client.oa;

import com.alibaba.fastjson.JSONObject;
import com.rkhd.platform.sdk.ScheduleJob;
import com.rkhd.platform.sdk.exception.ApiEntityServiceException;
import com.rkhd.platform.sdk.exception.ScriptBusinessException;
import com.rkhd.platform.sdk.http.RkhdHttpClient;
import com.rkhd.platform.sdk.http.RkhdHttpData;
import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;
import com.rkhd.platform.sdk.param.ScheduleJobParam;
import com.rkhd.platform.sdk.service.FutureTaskService;
import com.rkhd.platform.sdk.service.XoqlService;
import com.rkhd.platform.sdk.task.FutureTask;

import java.util.*;

/**
 * @Description 检查是否需要发送邮件通知
 * @Author 黎炎松
 * 2024-08-19 15:42
 */
public class CheckIsNeedSendEmail implements ScheduleJob, FutureTask {

    private static XoqlService xoqlService = XoqlService.instance();

    private static final Logger logger = LoggerFactory.getLogger();

    private static final String LOGGER_MSG = "检查创建时间是否距离当前已经超过2个小时 ==> ";


    /**
     * 计划作业
     * @param scheduleJobParam
     */
    @Override
    public void execute(ScheduleJobParam scheduleJobParam) {
        try {
            logger.info(LOGGER_MSG + "触发计划作业");
            String messageId = FutureTaskService.instance().addFutureTask(getClass(), "");
            logger.info(LOGGER_MSG + "异步ID:" + messageId);
        } catch (Exception e) {
            logger.error(LOGGER_MSG + " ----- 发生异常：" + e.getMessage());
        }
    }

    /**
     * 异步任务
     * @param s
     * @throws ScriptBusinessException
     */
    @Override
    public void execute(String s) throws ScriptBusinessException {
        logger.info(LOGGER_MSG + "执行异步任务");
        checkCreateTime();
    }

    
    public static void main(String[] args) throws ApiEntityServiceException {
        new CheckIsNeedSendEmail().checkCreateTime();
    }


    /**
     * 检查创建时间是否距离当前已经超过2个小时且没有提交到OA审批的(更改标识后，管理端设置触发规则进行邮件发送)
     */
    public void checkCreateTime() {
        try {
            logger.info(LOGGER_MSG + "处理开始");
            long timestamp = System.currentTimeMillis();
            long hoursTamp = 1000 * 60 * 60; // 小时
            long startTime = 1723910400000L; // 只查询2024-08-18之后的数据，之前的不处理

            // 循环修改几个模块的字段值
            List<String> objKeyList = Arrays.asList("quote", "contract", "_order", "bidSeal__c", "campaign", "customEntity39__c", "sporadicProcurement__c", "debooking__c");
            for (String objKey : objKeyList) {
                logger.info(LOGGER_MSG + "objKey: " + objKey);

                String sql = String.format("select id from %s where oaApprovalStatus__c = 7 and emailNotification__c = 0 and createdAt > %s and (%s - createdAt) / %s > 2", objKey, startTime, timestamp, hoursTamp);
                List<JSONObject> recordList = xoqlService.query(sql).getRecords();
                logger.info(LOGGER_MSG + "recordList: " + recordList);
                if (recordList.size() <= 0) {
                    continue;
                }

                // 拼接批量修改数据
                List<JSONObject> objectList = new ArrayList<>();
                for (JSONObject jsonObject : recordList) {
                    jsonObject.put("emailNotification__c", 1);

                    JSONObject data =  new JSONObject();
                    data.put("data", jsonObject);
                    objectList.add(data);
                }
                logger.info(LOGGER_MSG + "objectList: " + objectList);
                beacthUpdate(objectList, objKey.equals("_order") ? "order": objKey);
            }

            logger.debug(LOGGER_MSG + "处理成功");
        } catch (Exception e) {
            logger.error(LOGGER_MSG + "同步异常: " + e.getMessage());
        }
    }

    /**
     * 批量修改对象的数据
     * @param body
     * @param apiKey
     * @throws Exception
     */
    public void beacthUpdate(List<JSONObject> body,String apiKey) throws Exception {
        logger.info("apiKey：" + apiKey);
        logger.info("需要更新的数据：" + body.toString());
        JSONObject params = new JSONObject();
        params.put("batchData", body);
        RkhdHttpClient httpClient = new RkhdHttpClient();
        RkhdHttpData data  = RkhdHttpData.newBuilder()
                .callType("PATCH")
                .header("xsy-execmode", "continue") //允许部分失败
                .callString("/rest/data/v2.0/xobjects/" + apiKey + "/batch")
                .body(params.toJSONString())
                .build();
        String execute = httpClient.execute(data, e -> e);
        logger.info("更新结果：" + execute);
        JSONObject result = JSONObject.parseObject(execute);
        if(result.getInteger("code") != 200){
            throw new RuntimeException(result.getString("msg"));
        }
    }

}
